package cn.edu.ptu.jobfairs.core.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Slf4j
@Component
public class MD5PasswordEncoder implements PasswordEncoder {

    @Override
    public String encode(CharSequence rawPassword) {
        byte[] secretBytes;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(rawPassword.toString().getBytes());
            secretBytes = md.digest();
        } catch (NoSuchAlgorithmException e) {
            log.error("md5算法不可用");
            throw new RuntimeException("md5算法不可用");
        }
        String md5code = new BigInteger(1, secretBytes).toString(16);
        if (md5code.length() == 32) return md5code;
        StringBuilder zero = new StringBuilder();
        for (int i = 0; i < 32 - md5code.length(); i++) {
            zero.append('0');
        }
        return zero.toString() + md5code;
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        return rawPassword.equals(encodedPassword);
    }
}
